import 'package:cloud_medicine/components/cartItem.dart';
import 'package:cloud_medicine/components/chat_with_shop.dart';
import 'package:cloud_medicine/components/kind_tab.dart';
import 'package:cloud_medicine/components/shop_detail.dart';
import 'package:cloud_medicine/components/shop_picture.dart';
import 'package:cloud_medicine/components/shop_searchbar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/medicine_list.dart';
import 'package:cloud_medicine/model/shop_detail.dart';
import 'package:cloud_medicine/pages/medicine_add.dart';
import 'package:cloud_medicine/pages/shop_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'medicine_detail.dart';

class ShopDetail extends StatefulWidget {
  final num shopid;
  final bool isManage;

  ShopDetail({Key key, @required this.shopid, this.isManage = false})
      : super(key: key);

  @override
  _ShopDetailState createState() => _ShopDetailState();
}

class _ShopDetailState extends State<ShopDetail> with TickerProviderStateMixin {
  TabController _tabController;
  static ShopItem shopItem;
  bool _loading = false;
  bool _loading2 = false;
  bool _isCollect = false;
  List<MedicineItem> medicineItemList = [];

  Future<Null> _init() async {
    setState(() {
      _loading2 = true;
    });
    medicineItemList.clear();
    dynamic respon = await getShopInfo_api(
        '$backIP/shop/getShopInfo', {'ID': widget.shopid}); //接口路径
    shopItem = ShopItem.init(respon['data']);
    _isCollect = shopItem.isCollect;
    setState(() {
      _loading2 = false;
    });
  }

  Future<Null> _loadMedicineData(int kind) async {
    setState(() {
      _loading = true;
    });
    medicineItemList.clear();
    dynamic res = await getMedicineList_api('$backIP/shop/medicineListInShop',
        {'shopID': widget.shopid, 'kind': kind}); //接口路径
    res['data'].forEach((dynamic medicineItem) {
      MedicineItem medicineItemModel = MedicineItem.init(medicineItem);
      medicineItemList.add(medicineItemModel);
    });

    setState(() {
      _loading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    _init();
    _loadMedicineData(1);
    _tabController = TabController(length: 4, vsync: this);
    _tabController.addListener(() {
      if(_tabController.index ==_tabController.animation.value) {
        _loadMedicineData(_tabController.index + 1);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  bool isShop = user == null ? false : user.identify.id == 5;

  static _buildDeliverFeeText() {
    String iniDeliveryFeeText =
        shopItem == null ? '0' : shopItem.iniDeliveryFee.toString();
    return Text(
      '￥$iniDeliveryFeeText 起送',
      style: TextStyle(color: Colors.white),
      textAlign: TextAlign.right,
    );
  }

  static Widget _iniDelivery2 = ToStringFixed(
    mynum: shopItem.iniDeliveryFee - totalprice,
  );

  static List<Map<String, dynamic>> cartlist = [];
  static List judgeRepeat = []; //用于判断购物车中是否有重复商品

  Widget _rightText;

  static num totalprice = 0;
  static num cartnumber = 0;

  Future _collectOrCancel(num id) async {
    await collectOrCancel_api('$backIP/shop/collectShop', {'shopID': id});
  }

  Future _deleteMedicine(num medicineid) async {
    await deleteMedicine_api(
        '$backIP/shopManage/deleteMedicine', {"ID": medicineid});
  }

  List<Widget> _headerSliverBuilder(
      BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        automaticallyImplyLeading: true,
        title: ShopSearch(
          boxWidth: 124,
          hintTEXT: '搜店内药品',
        ),
        actions: <Widget>[
          Container(
              margin: EdgeInsets.all(0),
              child: !isShop
                  ? IconButton(
                      padding: EdgeInsets.all(0),
                      color: _isCollect ? Colors.yellow[500] : Colors.white,
                      icon: _isCollect
                          ? Icon(Icons.star)
                          : Icon(Icons.star_border),
                      onPressed: () {
                        _collectOrCancel(widget.shopid);
                        Fluttertoast.showToast(
                          msg: _isCollect ? '取消收藏成功' : '收藏成功',
                          backgroundColor: Colors.black,
                          textColor: Colors.white,
                        );
                        setState(() {
                          _isCollect = !_isCollect;
                        });
                      })
                  : Container())
        ],
        flexibleSpace: FlexibleSpaceBar(
          centerTitle: true,
          background: GestureDetector(
              child:
                  ShopDetailImg(imgUrl: shopItem.image, boxFit: BoxFit.cover),
              onTap: () {
                bool isManage;
                if (!widget.isManage) {
                  isManage = false;
                } else {
                  isManage = true;
                }
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) =>
                        ShopInfo(shopid: widget.shopid, isManage: isManage)));
              }),
        ),
        pinned: true,
        expandedHeight: 150,
        bottom: TabBar(
            controller: _tabController,
            isScrollable: true,
            tabs: kindTab,
            labelColor: Colors.white,
            labelStyle:
                TextStyle(fontSize: 15, fontWeight: FontWeight.w600, shadows: [
              Shadow(color: Colors.black, offset: Offset(1, 1), blurRadius: 50)
            ])),
      )
    ];
  }

  _gridLayout() {
    if(_loading) {
      return loadingWidget(_loading);
    }else{
      return GridView.builder(
          itemBuilder: ((BuildContext context, int index) {
            return Stack(
                alignment: AlignmentDirectional.center,
                fit: StackFit.expand,
                children: <Widget>[
                  InkWell(
                      splashColor: Colors.yellow.withOpacity(0.3),
                      highlightColor: Colors.yellow.withOpacity(0.1),
                      onTap: () {
                        bool isManage;
                        if (!widget.isManage) {
                          isManage = false;
                        } else {
                          isManage = true;
                        }
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => MedicineDetail(
                                medicineId: medicineItemList[index].id,
                                isManage: isManage)));
                      },
                      child: MedicineShow(
                          imgUrl: medicineItemList[index].mainimg,
                          name: medicineItemList[index].name,
                          number: medicineItemList[index].number,
                          price: medicineItemList[index].price)),
                  Positioned(
                      height: 25,
                      width: 25,
                      bottom: 10,
                      right: 15,
                      child: !isShop
                          ? FloatingActionButton(
                          heroTag: '$index',
                          //There are multiple heroes that share the same tag within a subtree.
                          backgroundColor: Colors.yellow[600],
                          tooltip: '加入购物车',
                          elevation: 5,
                          child: Icon(
                            Icons.add,
                            size: 25,
                          ),
                          onPressed: () {
                            setState(() {
                              bool ishave = judgeRepeat
                                  .contains(medicineItemList[index].id);
                              if (ishave) {
                                cartlist.map((f) {
                                  if (f['id'] == medicineItemList[index].id)
                                    f['number']++;
                                }).toList();
                              } else {
                                cartlist.add({
                                  'id': medicineItemList[index].id,
                                  'name': medicineItemList[index].name,
                                  'price': medicineItemList[index].price,
                                  'picture': medicineItemList[index].mainimg,
                                  'number': 1
                                });
                                judgeRepeat.add(medicineItemList[index].id);
                              }
                              totalprice =
                                  totalprice + medicineItemList[index].price;
                              cartnumber++;
                              _rightText =
                              totalprice < shopItem.iniDeliveryFee
                                  ? _iniDelivery2 = ToStringFixed(
                                mynum: shopItem.iniDeliveryFee -
                                    totalprice,
                              )
                                  : MyContainer(
                                allprice: totalprice +
                                    shopItem.deliveryFee,
                                cartList: cartlist,
                                deliveryFee: shopItem.deliveryFee,
                                shopname: shopItem.name,
                                shopID: widget.shopid,
                                clearCart: (value) =>
                                    _showbottomSheet(),
                              );
                            });
                          })
                          : widget.isManage
                          ? FloatingActionButton(
                        heroTag: '$index',
                        backgroundColor: Colors.red[600],
                        tooltip: '删除药品',
                        elevation: 5,
                        onPressed: () {
                          openAlertDialog(context, () {
                            _deleteMedicine(medicineItemList[index].id);
                            setState(() {
                              medicineItemList.removeAt(index);
                            });
                          }, "确认删除该药品吗？");
                        },
                        child: Icon(Icons.remove_circle_outline),
                      )
                          : Container())
                ]);
          }),
          itemCount: medicineItemList.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2, crossAxisSpacing: 15, mainAxisSpacing: 0));
    }
  }

  Widget _childLayout() {
    if (_loading2) {
      return Center(
          child: Container(
              child: Center(
        child: CircularProgressIndicator(),
      )));
    } else {
      return NestedScrollView(
          headerSliverBuilder: _headerSliverBuilder,
          body: TabBarView(
            controller: _tabController,
            children: [
              _gridLayout(),
              _gridLayout(),
              _gridLayout(),
              _gridLayout(),
            ],
          ));
    }
  }

  _showbottomSheet() {
    cartlist.clear();
    judgeRepeat.clear();
    totalprice = 0;
    cartnumber = 0;
    _rightText = _buildDeliverFeeText();
  }

  _floatingActionButton() {
    if (_loading2) {
      return Container();
    } else {
      return shopItem == null
          ? Container()
          : !isShop
              ? Padding(
                  padding: EdgeInsets.only(right: 10),
                  child: Card(
                    color: Colors.black,
                    margin: EdgeInsets.only(top: 10),
                    child: SizedBox(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 70,
                        child: Row(children: <Widget>[
                          SizedBox(
                            width: 15,
                          ),
                          ChatWithShop(
                            id: widget.shopid,
                            picture: shopItem.image,
                            shopname: shopItem.name,
                          ),
                          VerticalDivider(
                            // width: 10,
                            thickness: 3,
                            color: Colors.white,
                          ),
                          InkWell(
                              child: Row(children: <Widget>[
                                Column(children: <Widget>[
                                  CartListText(
                                    text: totalprice.toStringAsFixed(2),
                                    size: 19,
                                  ),
                                  CartListText(
                                    text: shopItem.deliveryFee == 0
                                        ? '免配送费'
                                        : '还需配送费￥${shopItem.deliveryFee}',
                                  )
                                ]),
                                SizedBox(
                                  width: 17,
                                )
                              ]),
                              onTap: () {
                                showModalBottomSheet(
                                    context: context,
                                    builder: (context) => StatefulBuilder(
                                            builder:
                                                (context, setBottomSheetstate) {
                                          //解决bottomsheet的setstate没有用的问题
                                          //setstate还是整个页面的刷新，不是showModalBottomSheet中的刷新，所以需要在showModalBottomSheet中重新定义刷新方法，然后调用此方法刷新即可
                                          return Container(
                                              margin: EdgeInsets.all(10),
                                              height: 130 *
                                                  cartlist.length.toDouble(),
                                              child: SingleChildScrollView(
                                                  child:
                                                      Column(children: <Widget>[
                                                Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceBetween,
                                                    children: <Widget>[
                                                      Container(
                                                        child: Text(
                                                            '购物车(共$cartnumber 件药品)'),
                                                      ),
                                                      InkWell(
                                                          onTap: () {
                                                            setBottomSheetstate(
                                                                () {
                                                              _showbottomSheet();
                                                            });
                                                            setState(() {
                                                              _showbottomSheet();
                                                            });
                                                          },
                                                          child: Row(children: <
                                                              Widget>[
                                                            Icon(Icons.delete),
                                                            Text('清空购物车')
                                                          ]))
                                                    ]),
                                                Column(
                                                  children:
                                                      cartlist.map((index) {
                                                    return CartItem(
                                                        imgUrl:
                                                            index['picture'],
                                                        name: index['name'],
                                                        price: index['price'],
                                                        medicineNumber:
                                                            index['number'],
                                                        medicineID: index['id'],
                                                        addcallback: (value) {
                                                          setState(() {
                                                            totalprice +=
                                                                index['price'];
                                                            index['number']++;
                                                          });
                                                          setBottomSheetstate(
                                                              () {
                                                            cartnumber++;
                                                          });
                                                        },
                                                        removecallback:
                                                            (value) {
                                                          setState(() {
                                                            totalprice -=
                                                                index['price'];
                                                            if (index[
                                                                    'number'] >
                                                                1) {
                                                              index['number']--;
                                                            } else {
                                                              cartlist.remove(
                                                                  index);
                                                              judgeRepeat
                                                                  .remove(index[
                                                                      'id']);
                                                            }
                                                          });
                                                          setBottomSheetstate(
                                                              () {
                                                            cartnumber--;
                                                          });
                                                        });
                                                  }).toList(),
                                                ),
                                                Divider(
                                                  thickness: 2,
                                                )
                                              ])));
                                        }));
                              }),
                          _rightText = totalprice == 0
                              ? _buildDeliverFeeText()
                              : totalprice < shopItem.iniDeliveryFee
                                  ? _iniDelivery2
                                  : MyContainer(
                                      allprice:
                                          totalprice + shopItem.deliveryFee,
                                      cartList: cartlist,
                                      deliveryFee: shopItem.deliveryFee,
                                      shopname: shopItem.name,
                                      shopID: widget.shopid,
                                      clearCart: (value) => _showbottomSheet(),
                                    )
                        ])),
                    shape: StadiumBorder(),
                  ))
              : widget.isManage
                  ? Container(
                      margin: EdgeInsets.only(left: 30),
                      width: double.infinity,
                      child: RaisedButton(
                          color: Colors.blue,
                          child: Text('添加药品',
                              style: TextStyle(color: Colors.white)),
                          onPressed: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => MedicineAdd()));
                          }))
                  : Container();
    }
  }

  Future<bool> _pop() async {
    setState(() {
      _showbottomSheet();
    });
    Navigator.pop(context);
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        body: _childLayout(),
        floatingActionButton: _floatingActionButton(),
      ),
      onWillPop: _pop,
    );
  }
}
